﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public abstract class SpeedCheck : MonoBehaviour
{
    [SerializeField]
    protected Axis m_Axis;
    [SerializeField, Range(-1f, 1f)]
    protected float m_Direction;
    [HideInInspector]
    public UnityEvent OnSpeedPass;
    [HideInInspector]
    public bool IsPass = false;
    protected float enterSpeed, exitSpeed;

    SpriteRenderer spriteRenderer;

    protected virtual void Awake()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
    }

    protected abstract bool CheckSpeed();

    public void ResetColor()
    {
        spriteRenderer.color = new Color(1, 1, 1, 0.5f);
    }
    protected void OnTriggerEnter2D(Collider2D collision)
    {
        if (enabled && collision.attachedRigidbody != null)
        {
            Vector2 velocity = collision.attachedRigidbody.velocity;
            switch (m_Axis)
            {
                case Axis.X:
                    enterSpeed = velocity.x;
                    break;
                case Axis.Y:
                    enterSpeed = velocity.y;
                    break;
            }
            enabled = Mathf.Sign(enterSpeed) != Mathf.Sign(m_Direction);//方向不一样是不行的
            enterSpeed = Mathf.Abs(enterSpeed);
        }
    }
    protected void OnTriggerExit2D(Collider2D collision)
    {
        if (enabled && collision.attachedRigidbody != null)
        {
            Vector2 velocity = collision.attachedRigidbody.velocity;
            switch (m_Axis)
            {
                case Axis.X:
                    exitSpeed = Mathf.Abs(velocity.x);
                    break;
                case Axis.Y:
                    exitSpeed = Mathf.Abs(velocity.y);
                    break;
            }
            exitSpeed += enterSpeed;
            exitSpeed /= 2f;
            if (CheckSpeed())
            {
                IsPass = true;
                spriteRenderer.color = new Color(0, 1, 0, 0.5f);
                OnSpeedPass.Invoke();
            }
            else
                spriteRenderer.color = new Color(1, 0, 0, 0.5f);
            enabled = false;
        }
    }
}
public enum Axis
{
    X,
    Y
}
